class TicketController < ApplicationController
  before_filter :web_user_authorize,:except =>[:flight_query]
  
  def searchAirLineWeb
    begin
      fromto = params[:fromto]
      date = CommonHelper.getCmdDateFormat(params[:date])
      airways_code = params[:airways_code]
      seat = params[:seat]
      airportFrom = Airport.find_by_code(fromto[0,3])
      airportTo = Airport.find_by_code(fromto[3,3])
      fromAirport = airportFrom.airport_name
      toAirport = airportTo.airport_name
      
      #logger.error fromto
      #logger.error date
      #logger.error airways_code
      #logger.error fromAirport
      #logger.error toAirport
      #logger.error seat
      
      rootStr = "[]"
      result = "successful"
      if airways_code && airways_code!=""
        cmd = "AVH/"+fromto+"/"+date+"/"+airways_code+"/D"
      else
        cmd = "AVH/"+fromto+"/"+date+"/D"
      end
      #logger.error "---查询命令cmd="+cmd
      rubySocket = SocketHelper.getSocket(session[:eterm_name],session[:eterm_pswd])
      if rubySocket
        restring = CommonHelper.getAvhResult(rubySocket,cmd,date)
        if rubySocket
          rubySocket.close
          rubySocket = nil
        end
        #logger.error "============ searchAirLineWeb ==============="
        #logger.error restring
        if restring.index("失败 ")
          result = restring[restring.index(" ")+1..-1]
        else
          jsonStr = "["
          while(restring.index("<br>"))
            subQueryResultStr = restring[0,restring.index("<br>")].strip
            #logger.error "=============== line ===================="
            #logger.error subQueryResultStr
            #行内容里面必须包含城市对 除了上海有两个机场
            if subQueryResultStr.index(" ") && (fromto.index("SHA") || subQueryResultStr.index(" "+fromto+" "))
              fromtoNum = 0
              offset = subQueryResultStr.index(" ")
              air_no = subQueryResultStr[0,offset]
              #不处理带×号的航班
              if air_no.index("*")==nil && rootStr.index("'"+air_no+"'")==nil
                airways_code = air_no[0,2]
                airway = Airways.find_by_code(airways_code)
                #logger.error "air_no="+air_no
                #logger.error airway.airways_name
                
                ############ 分析行 ############
                if subQueryResultStr.index("S#")
                  offset = subQueryResultStr.index("S#")+3
                elsif subQueryResultStr.index("S*")
                  offset = subQueryResultStr.index("S*")+3
                else
                  offset += 5
                end
                fromtoNum = 0
                if subQueryResultStr.index(" "+fromto+" ")
                  fromtoNum = subQueryResultStr.index(" "+fromto+" ")
                elsif fromto.index("SHA")
                  fromtoNum = subQueryResultStr.index(" "+fromto.gsub(/SHA/,"PVG")+" ")
                end
                if fromtoNum>offset
                  plane_type = subQueryResultStr[18+fromtoNum,4].strip
                  #仓位信息字段
                  positionStr = subQueryResultStr[offset..fromtoNum].strip
                  if subQueryResultStr.index("-----")
                    statusOther = subQueryResultStr[subQueryResultStr.index("-----")+5..-1].strip
                    statusOther = statusOther[0,statusOther.index("--")].strip if statusOther.index("--")
                    positionStr << " "+statusOther
                  end
                  positionStr = " "+positionStr
                  #logger.error positionStr
                
                  #得到航空公司舱位表，由低价舱到高价舱
                  positionArr = CommonHelper.getDiscountArray(airways_code)
                  for position in positionArr
                    position_code = position.position_code
                    discount = position.discount
                    #logger.error "position_code="+position_code
                    if positionStr.index(" "+position_code)
                      k = positionStr[positionStr.index(" "+position_code)+1,2]
                      #logger.error "--"+k
                      if k[1,1]=="A" || (k[1,1].to_i>=seat.to_i && k[1,1].to_i<=9)
                      
                        sql = "is_locked<>1"
                        #sql << " and airport_from like '%"+fromAirport+"%' and airports_to like '%"+toAirport+"%'"
                        sql << " and airways_id="+airway.id.to_s+" and airport_from_id="+airportFrom.id.to_s+" and airports_to like '%"+toAirport+"%'"
                        sql << " and ((discount_from<="+discount.to_s+" and discount_to>="+discount.to_s+") or (discount_from>="+discount.to_s+" and discount_to<="+discount.to_s+"))"
                        #logger.error "sql="+sql
                        webPriceRelease = WebPriceRelease.find(:first,:conditions=>sql)
                        if webPriceRelease
                          #返点率
                          rake_off = webPriceRelease.rake_off
                          #logger.error "rake_off="+rake_off.to_s
                          #舱位价格
                          positionPrice = PositionPrice.find(:first,:conditions=>["airways_code=? and position=? and fromto=?",airways_code,position_code,fromto])
                          #logger.error positionPrice
                          #logger.error "plane_type="+subQueryResultStr[18+fromtoNum,3]
                          #logger.error "fly_time="+subQueryResultStr[8+fromtoNum,4]
                          #logger.error "arr_time="+subQueryResultStr[13+fromtoNum,4]
                          #logger.error "fromAirport="+fromAirport
                          #logger.error "toAirport="+toAirport
                          if positionPrice && positionPrice.price
                            price = positionPrice.price.to_s
                            #logger.error "price="+price
                            jsonStr << "," if jsonStr!="["
                            jsonStr << "{\"air_no\":\"#{air_no}\",\"plane_type\":\"#{plane_type}\",\"fly_time\":\"#{subQueryResultStr[8+fromtoNum,2]}:#{subQueryResultStr[10+fromtoNum,2]}\",\"arr_time\":\"#{subQueryResultStr[13+fromtoNum,2]}:#{subQueryResultStr[15+fromtoNum,2]}\","
                            jsonStr << "\"airport\":\"#{fromAirport} - #{toAirport}\",\"price\":#{price},\"rake_off\":#{rake_off},"
                            jsonStr << "\"discount\":#{discount},\"airways_name\":\"<img src='\/images\/airways\/#{airways_code}.gif' width=15 height=15\/>#{airway.airways_name}\",\"position\":\"#{position_code}\"}"
                            break
                          end
                        end
                      end
                    end
                  end
                end
                ############ 分析结束 ############
              end
            end
            
            restring = restring[restring.index("<br>")+4..-1].strip
          end
          jsonStr << "]"
        end
      else
        result = "连接放大器失败,或用户已被占用!"
      end
      #logger.error "============searchAirLineWeb ending !!!!!!!!==============="
      #logger.error jsonStr
      jsonstr="{root:"+jsonStr+",info:'"+result+"'}"
      render :text=>jsonstr, :layout=>false
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
      rubySocket.close if rubySocket
      logger.error e.message
    end
  end
  
  def add_order
    begin
      
      @airNo = params[:airNo]
      @fromto = params[:fromto]
      @fly_date = params[:fly_date]
      @fly_time = params[:fly_time]
      @arr_time = params[:arr_time]
      @plane_type = params[:plane_type]
      @price = params[:price]
      @position = params[:position]
      @rake_off = params[:rake_off]
      
      logger.error @airNo
      logger.error @fly_date
      logger.error @fromto
      logger.error @position
      logger.error @fly_time
      logger.error @arr_time
      logger.error @plane_type
      logger.error @price
      logger.error @rake_off
      
      from = @fromto[0,3]
      to = @fromto[3,3]
      
      @airdrome_tax = CommonHelper.getPlaneTax(@plane)
      @fuel_tax = CommonHelper.getFuelTax(@fromto)
      @airways = Airways.find_by_code(@airNo[0,2])
      @from_airport = Airport.find_by_code(from)
      @to_airport = Airport.find_by_code(to)
      
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
    end
  end
  
  def save_order
    begin
      logger.error ">>>>>> save_order >>>>>>"
      airNo = params[:airNo]
      fly_date = params[:fly_date]
      fromto = params[:fromto]
      position = params[:position]
      arr_time = params[:arr_time]
      fly_time = params[:fly_time]
      plane_type = params[:plane_type]
      price = params[:price]
      rake_off = params[:rake_off]
      seat = params[:seat_number]
      link_man = params[:link_man]
      link_tel = params[:link_tel]
      link_email = params[:link_email]
      link_address = params[:link_address]
      
      logger.error airNo
      logger.error fly_date
      logger.error fromto
      logger.error position
      logger.error fly_time
      logger.error arr_time
      logger.error plane_type
      logger.error price
      logger.error rake_off
      logger.error seat
      logger.error link_man
      logger.error link_tel
      logger.error link_email
      logger.error link_address
      
      airways_code = airNo[0,2]
      logger.error "airways_code="+airways_code

      fly_date_cmd = CommonHelper.getCmdDateFormat(fly_date)

      #出票时限
      curTime = Time.new
      today = curTime.strftime("%Y-%m-%d").to_s
      toHour = curTime.strftime("%H").to_i+2
      toMin = curTime.strftime("%M").to_s
      if toHour>=24
        tktl_date = (today.to_date+1).to_date.to_s
        tktl_time = "00"+toMin if toHour==24
        tktl_time = "01"+toMin if toHour==25
        tktl_time = "02"+toMin if toHour==26
      else
        tktl_date = today.to_s
        if toHour<10
          tktl_time = "0"+toHour.to_s+toMin
        else
          tktl_time = toHour.to_s+toMin
        end
      end
      tktl_date = CommonHelper.getCmdDateFormat(tktl_date)
      tktl_time = "2300" if tktl_time==nil
      logger.error tktl_date
      logger.error tktl_time
      
      result = ""
      ################### 循环获取乘客姓名 获取拼音并转化编码 ######################
      logger.error "循环获取乘客姓名 获取拼音并转化编码"
      nameString = ""
      cardString = ""
      humanTypeString = ""
      insuranceString = ""
      birthdayString = ""
      nmStr = "nm" #穿入名字命令
      cardStr = "" #穿入证件号命令
      cardStr2 = "" #穿入证件号命令2
      babyStr = "" #婴儿命令
      babyStr2 = "" #婴儿命令2
      
      i_number = 0 #保险总数
      baby_no = 0
      seat_cmd = seat.to_i
      for i in 1..seat.to_i
        logger.error "====seat for=="+i.to_s+"===="
        passenger_name = params["pessenger_name_"+i.to_s]
        human_type = params["age_type_"+i.to_s]
        birthday = params["birthday_"+i.to_s]
        birthday = "" if birthday==nil
        id_card = params["card_"+i.to_s]
        id_card = "" if id_card==nil
        insurance_number = params["insurance_"+i.to_s]
        
        logger.error passenger_name
        logger.error human_type
        logger.error birthday
        logger.error id_card
        logger.error insurance_number
        
        i_number += insurance_number.to_i
        nameString << "," if i>1
        nameString << passenger_name
        birthdayString << "," if i>1
        birthdayString << birthday
        cardString << "," if i>1
        cardString << id_card
        humanTypeString << "," if i>1
        humanTypeString << human_type
        insuranceString << "," if i>1
        insuranceString << insurance_number
        
        pass_name = SocketHelper.getTransChineseName(passenger_name)
        if human_type=="婴儿"
          #if birthday.to_date>(today.to_date-365)
          #婴儿
          if passenger_name.index("/")
            name_pinyin = passenger_name
          else
            xing = SocketHelper.getPinYin(passenger_name[0,3])
            ming = SocketHelper.getPinYin(passenger_name[3..-1])
            name_pinyin = xing+"/"+ming
          end
          seat_cmd -= 1 #婴儿不算座位
          baby_no += 1
          baby_date_cmd = CommonHelper.getCmdDateFormat(birthday)
          babyStr << Constants::SEPARATE_KEY
          babyStr << "XN:IN/"+pass_name+"INF("+baby_date_cmd[2,5]+")/P"+baby_no.to_s
          babyStr << Constants::SEPARATE_KEY
          babyStr << "SSR INFT "+airNo[0,2]+" NN1 "+fromto+" "+airNo[2..-1]+" "+position+fly_date_cmd+" "+name_pinyin+" "+baby_date_cmd+"/P"+baby_no.to_s
        elsif human_type=="儿童"
          #儿童
          nmStr << "1"+pass_name
          #pass_name << "(UM4)"  #UM指无人陪伴的儿童；4指年龄
          chd_date_cmd = CommonHelper.getCmdDateFormat(birthday)
          nmStr << "CHD("+chd_date_cmd+")"
        else
          if human_type=="教师"
            nmStr << "1"+pass_name+"YDT"
          elsif human_type=="学生"
            nmStr << "1"+pass_name+"YSD"
          else
            nmStr << "1"+pass_name
          end
          if seat.to_i==1
            if id_card && id_card!=""
              cardStr << Constants::SEPARATE_KEY
              cardStr << "SSR FOID "+airNo[0,2]+" HK/NI"+id_card
            end
          else
            if id_card && id_card!=""
              card_no = i-baby_no #减去婴儿的数量才是正确的编号
              cardStr << Constants::SEPARATE_KEY
              cardStr << "SSR FOID "+airNo[0,2]+" HK/NI"+id_card+"/P"+card_no.to_s
            end
          end
        end
      end
      logger.error "循环结束,结果如下====="
      logger.error "nmStr="+nmStr
      logger.error "cardStr="+cardStr
      logger.error "cardStr2="+cardStr2
      logger.error "babyStr="+babyStr
      logger.error "babyStr2="+babyStr2
      logger.error nameString
      logger.error humanTypeString
      logger.error cardString
      logger.error birthdayString
      logger.error insuranceString
      
      #定航段的SS命令后面的所有命令
      tail_cmd = ""
      tail_cmd << Constants::SEPARATE_KEY
      tail_cmd << nmStr
      tail_cmd << Constants::SEPARATE_KEY
      tail_cmd << "ct/81115555-"+session[:web_user_id].to_s
      tail_cmd << Constants::SEPARATE_KEY
      tail_cmd << "tktl/"+tktl_time+"/"+tktl_date+"/tao220"
      if cardStr!=""
        tail_cmd << cardStr
      end
      if babyStr!=""
        tail_cmd << babyStr
      end
      tail_cmd << Constants::SEPARATE_KEY
      tail_cmd << "@"
      
      #s = Rjb::import("PlaneSocket")
      #p = s.new(Constants::SERVER_INFO,Constants::SERVER_PORT,Constants::USERNAME,Constants::PASSWORD)
      cmd = "ss"+airNo+position+fly_date_cmd+fromto+seat_cmd.to_s
      cmd << tail_cmd
      
      logger.error "-----订票命令cmd="+cmd
      rubySocket = SocketHelper.getSocket(session[:eterm_name],session[:eterm_pswd])
      if rubySocket
        res = SocketHelper.getCR(rubySocket,"i",false)
        logger.error "----"+res
        restr = SocketHelper.getCR(rubySocket,cmd,true)
        if rubySocket
          rubySocket.close
          rubySocket=nil
        end
        logger.error "----订票结果="+restr
      else
        restr = ""
      end
      restr = CommonHelper.getPnrFromSocketResult(restr,airNo,nil,nil,nil)
      if restr.index(" ") && restr.index(" ")==5
        pnr = restr[0,5]
      else
        pnr = ""
      end

      logger.error "-----提取PNR="+pnr+"-----"
      if pnr && pnr.length==5
        orderid = WebOrder.saveWebOrder(session[:web_user_id],pnr,airNo,fromto,fly_date,fly_time,arr_time,position,plane_type,link_man,link_tel,link_email,link_address,price,seat,i_number,tktl_date,tktl_time,rake_off)
        if orderid && orderid.to_i>0
          orderid = orderid.to_i
          logger.error "=======orderid="+orderid.to_s
          for i in 1..seat.to_i
            
            logger.error "====seat for=="+i.to_s+"===="
            passenger_name = params["pessenger_name_"+i.to_s]
            human_type = params["age_type_"+i.to_s]
            birthday = params["birthday_"+i.to_s]
            birthday = "" if birthday==nil
            id_card = params["card_"+i.to_s]
            id_card = "" if id_card==nil
            insurance_number = params["insurance_"+i.to_s]
            airdrome_tax = CommonHelper.getPlaneTax(plane_type)
            fuel_tax = CommonHelper.getFuelTax(fromto)

            logger.error passenger_name
            logger.error human_type
            logger.error birthday
            logger.error id_card
            logger.error insurance_number
            if human_type=="儿童"
              chd_price = CommonHelper.getChdPrice(airNo[0,2],fromto)
              chd_date_cmd = CommonHelper.getCmdDateFormat(birthday)
              passenger_name << "CHD("+chd_date_cmd+")"
              ticketid = WebTicket.saveWebTicket(orderid,pnr,passenger_name,"",id_card,chd_price,0,fuel_tax/2,insurance_number)
            else
              ticketid = WebTicket.saveWebTicket(orderid,pnr,passenger_name,"",id_card,price,airdrome_tax,fuel_tax,insurance_number)
            end
            if ticketid==nil || ticketid.to_i==0
              result = "保存票失败,PNR是#{pnr},乘客是#{passenger_name}(#{id_card})"
              break
            end
            logger.error "ticketid="+ticketid.to_s
          end
          if result.index("保存票失败")==nil
            result = "订票成功,PNR是#{pnr}"
            
            #更新订单总金额
            tickets = WebTicket.find_by_sql("select sum(total_price) as price_sum from web_tickets where web_order_id="+orderid.to_s+" and is_locked<>1")
            price_sum = tickets[0].price_sum
            logger.error "订单总金额="+price_sum.to_s
            WebOrder.update_all("price_sum="+price_sum.to_s,["id=?",orderid])
                    
          end
        else
          #TODO 如果保存订单失败，应该建立一个表单独保存已经生成的pnr，否则该pnr不会在系统中记录下来
          result = "保存订单失败,PNR是#{pnr}"
        end
      else
        result = "提取PNR失败,PNR是#{pnr}"
      end
      logger.error "result="+result
      result = "{success:true,info:'"+result+"'}"
      render :text=>result, :layout=>false
    rescue Exception => e
      logger.error e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
      rubySocket.close if rubySocket
    end
  end
  
  def cancel_order
    begin
      logger.error ">>>>> cancel_order >>>>>>"
      id = params[:id]
      logger.error id
      weborder = WebOrder.find_by_id(id)
      if weborder
        status = weborder.status
        if weborder.pnr
          logger.error weborder.pnr
          res = CommonHelper.getCancelPnrResult(weborder.pnr,session[:eterm_name],session[:eterm_pswd])
          logger.error "-----取消pnr结果res="+res
          if res.index("成功") || res.index("已经被取消")
            continueFlag = true
          else
            result = res+","+status
            #result = "取消pnr失败,"+status
          end
        else
          logger.error "-----该订单没有pnr记录"
          continueFlag = true
        end
        if continueFlag
          if weborder.status == Constants::WEB_ORDER_STATUS_DDZF
            weborder.status = Constants::WEB_ORDER_STATUS_KHSC
          else
            weborder.status = Constants::WEB_ORDER_STATUS_SQQX
          end
          weborder.cancel_date = Time.new
          weborder.canceler_id = session[:web_user_id] if session[:web_user_id]
          if weborder.save
            result = "取消订单成功,"+weborder.status
          else
            result = "取消订单失败,"+status
          end
        end
      else
        result = "订单不存在"
      end
      logger.error "result="+result
      render :text=>result, :layout=>false
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
      
    end
  end
  
  def draw_order
    begin
      logger.error ">>>>> draw_order >>>>>>"
      id = params[:id]
      logger.error id
      weborder = WebOrder.find_by_id(id)
      if weborder
        if params[:succ]
          weborder.status = Constants::WEB_ORDER_STATUS_TPWC
        else
          weborder.status = Constants::WEB_ORDER_STATUS_SQTP
        end
        if weborder.save
          result = "操作成功"
        else
          result = "保存失败"
        end
      else
        result = "订单不存在"
      end
      logger.error "result="+result
      render :text=>result, :layout=>false
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
    end
  end
  
  def cancel_ticket
    begin
      logger.error ">>>>>> cancel_ticket >>>>>>"
      id = params[:id]
      logger.error id
      ticket = WebTicket.find_by_id(id) if id
      if ticket
        pass_name = ticket.pass_name
        logger.error pass_name
        pnr = ticket.pnr
        logger.error pnr
        if pass_name && pnr && pnr!=""
          weborder = ticket.order
          if weborder.tickets.length==1
            logger.error "删除订单"
            res = CommonHelper.getCancelPnrResult(pnr,session[:eterm_name],session[:eterm_pswd])
          else
            logger.error "删除乘客"+pass_name
            res = CommonHelper.getCancelTicketResult(pnr,pass_name,session[:eterm_name],session[:eterm_pswd])
          end
          if res && res.index("成功")
            if ticket.destroy
              result = "操作成功"
            else
              logger.error "-----删除订票记录失败!!!!!"
            end
            #如果该订单只有这一张票，则订单也被取消
            if weborder.tickets.length==1
              if weborder.status == Constants::WEB_ORDER_STATUS_DDZF
                weborder.status = Constants::WEB_ORDER_STATUS_KHSC
              else
                weborder.status = Constants::WEB_ORDER_STATUS_SQQX
              end
              weborder.cancel_date = Time.new
              weborder.canceler_id = session[:web_user_id] if session[:web_user_id]
              if !weborder.save
                logger.error "!!!!!!!!!!!!!!!取消订单失败"
              end
            end
          else
            result = res
          end
        else
          result = "pnr不存在"
        end        
      else
        result = "编号为#{id}的票记录不存在"
      end
      logger.error "result="+result
      render :text=>result, :layout=>false
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
    end
  end
  
  #根据订单得到票
  def getTicketsByOrderID
    begin
      id = params[:id]
      logger.error ">>>>>>>>>>>>>>>>>>>>>>"+id
      rootStr = "[]"
      if id && id.to_i>0
        sql = "web_order_id="+id+" AND is_locked <> 1"
        tickets = WebTicket.find(:all,:conditions => sql)
        if tickets && tickets.length>0
          rootStr = tickets.to_json()
        end
      end
      jsonstr="{root:"+rootStr+"}"
      logger.error jsonstr
      render :text=>jsonstr, :layout=>false
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
    end
  end

  def getOrderInfoByPnr
    begin
      orderid = ""
      rootStr = ""
      pnr = params[:pnr]
      if pnr && pnr.length==5
        pnr = pnr.upcase
        #查询30天之内有没有重复的pnr
        today = Time.new.strftime("%Y-%m-%d")
        limit_date = (today.to_date-Constants::PNR_REPEAT_DAY).to_s
        order = WebOrder.find(:first,:conditions=>["pnr=? and created_at>?",pnr,limit_date])
        if order
          orderid = order.id
          info = "系统中已经存在#{pnr}的订单记录"
          rootStr = order.to_json(:include=>[:seller,:web_user])
        else
          info = CommonHelper.saveWebOrderByPnr(pnr,session[:web_user_id],session[:eterm_name],session[:eterm_pswd])
          if info.to_i>0
            #返回的是数字,则表示提取保存成功
            orderid = info.to_i
            order = WebOrder.find_by_id(orderid)
            info = "提取成功"
            rootStr = order.to_json(:include=>[:seller,:web_user])
          end
        end
      else
        info = "输入的PNR有误,必须是5为字母或数字组成!"
      end
      jsonstr="{root:["+rootStr+"],info:'"+info+"',orderid:'"+orderid.to_s+"'}"
      render :text=>jsonstr, :layout=>false
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
    end
  end
  
  #没有加个人权限,不过暂时处理
  def getEditTicketInfoByID
    begin
      id = params[:id]
      logger.error ">>>>>>> getEditTicketInfoByID >>>>>>>>>>"
      logger.error id
      rootStr = "[]"
      webticket = WebTicket.find_by_id(id) if id
      if webticket
        rootStr = webticket.to_json()
      end
      logger.error rootStr
      jsonstr="{root:["+rootStr+"]}"
      render :text=>jsonstr, :layout=>false
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
    end
  end
  
  #保存票中费用的修改结果
  def saveEditTicket
    begin
      logger.error "========:controller=#{params[:controller]},:action=#{params[:action]}========="
      id = params[:id]
      card = params[:pass_card_id]
      ticket_no = params[:ticket_no]
      result = "{success:false,info:'编辑失败'}"
      ticket = WebTicket.find_by_id(id) if id
      if ticket
        ticket.pass_card_id = card if card
        ticket.ticket_no = ticket_no if ticket_no
        if ticket.save
          result = "{success:true,info:'编辑成功'}"
        else
          result = "{success:true,info:'保存记录失败'}"
        end
      else
        result = "{success:true,info:'获取记录失败'}"
      end
      render :text=>result, :layout=>false
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
    end
  end
  
  #订票结果
  def result_order
    begin
      
      orderid = params[:orderid]
      @weborder = WebOrder.find_by_id(orderid)
      
      logger.error orderid
      logger.error @weborder
      
      if @weborder
        from = @weborder.fromto[0,3]
        to = @weborder.fromto[3,3]
        @airdrome_tax = CommonHelper.getPlaneTax(@weborder.plane_type)
        @fuel_tax = CommonHelper.getFuelTax(@weborder.fromto)
        @airways = Airways.find_by_code(@weborder.air_no[0,2])
        @from_airport = Airport.find_by_code(from)
        @to_airport = Airport.find_by_code(to)
      else
        @weborder = WebOrder.new
      end
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
      
    end
  end
  
  #查看订单
  def viewOrder
    begin
      
      id = params[:id]
      @weborder = WebOrder.find_by_id(id) if id
      
      logger.error id
      logger.error @weborder
      
      if @weborder
        from = @weborder.fromto[0,3]
        to = @weborder.fromto[3,3]
        @airdrome_tax = CommonHelper.getPlaneTax(@weborder.plane_type)
        @fuel_tax = CommonHelper.getFuelTax(@weborder.fromto)
        @airways = Airways.find_by_code(@weborder.air_no[0,2])
        @from_airport = Airport.find_by_code(from)
        @to_airport = Airport.find_by_code(to)
      else
        @weborder = WebOrder.new
      end
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
      
    end
  end
  
  #修改订单
  def modify_order
    begin
      
      id = params[:id]
      @weborder = WebOrder.find_by_id(id) if id
      
      logger.error id
      logger.error @weborder
      
      if @weborder
        from = @weborder.fromto[0,3]
        to = @weborder.fromto[3,3]
        @airdrome_tax = CommonHelper.getPlaneTax(@weborder.plane_type)
        @fuel_tax = CommonHelper.getFuelTax(@weborder.fromto)
        @airways = Airways.find_by_code(@weborder.air_no[0,2])
        @from_airport = Airport.find_by_code(from)
        @to_airport = Airport.find_by_code(to)
      else
        @weborder = WebOrder.new
      end
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
      
    end
  end
  
  def save_modify_order
    begin
      id = params[:id]
      weborder = WebOrder.find_by_id(id) if id
      link_man = params[:link_man]
      link_tel = params[:link_tel]
      link_email = params[:link_email]
      link_address = params[:link_address]
      
      logger.error id
      logger.error weborder
      logger.error link_man
      logger.error link_tel
      logger.error link_email
      logger.error link_address
      
      if weborder
        weborder.link_man = link_man
        weborder.link_tel = link_tel
        weborder.link_email = link_email
        weborder.link_address = link_address
        
        n = 1
        for t in weborder.tickets
          logger.error "----"+n.to_s
          logger.error params["identity"+n.to_s]
          logger.error params["call"+n.to_s]
          t.pass_card_id = params["identity"+n.to_s]
          t.pass_tel = params["call"+n.to_s]
          t.save
          n += 1
        end
        
        if weborder.save
          result = "保存成功"
        else
          result = "保存失败"
        end
      else
        result = "参数错误，订单不存在"
      end
      logger.error "result="+result
      render :text=>result, :layout=>false
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
      
    end
  end
  
  def search_by_other
    @airways = Airways.find(:all)
  end
  
  def getWebOrdersBySearch
    begin
      rootStr = ""
      web_user_id = session[:web_user_id]
      web_user_id = 1 if web_user_id==nil
      sql = "web_user_id="+web_user_id.to_s
      sql << " and status not in('"+Constants::WEB_ORDER_STATUS_KHSC+"')"
      #sql << " and status in('"+Constants::WEB_ORDER_STATUS_DDZF+"','"+Constants::WEB_ORDER_STATUS_ZFCG+"','"+Constants::WEB_ORDER_STATUS_CLWC+"')"
      if web_user_id
        if params[:order_no]
          order_no = params[:order_no]
          sql << " and order_no='"+order_no+"'"
        elsif params[:pnr]
          pnr = params[:pnr]
          sql << " and pnr='"+pnr+"'"
        elsif params[:passenger_name]
          pass_name = params[:passenger_name]
          pass_card = params[:passenger_card]
          sql << " and id in(select web_order_id from web_tickets where web_order_id is not null"
          sql << " and pass_name like '%"+pass_name+"%'" if pass_name && pass_name!=""
          sql << " and pass_card_id='"+pass_card+"'" if pass_card && pass_card!=""
          sql << ")"
        else
          fromdate = params[:date_begin]
          todate = params[:date_end]
          sql << " and created_at>='"+fromdate+"'" if fromdate && fromdate!=""
          sql << " and created_at<='"+todate+"'" if todate && todate!=""
        end
      end
      logger.error "sql="+sql
      weborders = WebOrder.find(:all,:conditions=>sql,:order=>"created_at desc")
      logger.error weborders.length
      for weborder in weborders
        from_airport = Airport.find_by_code(weborder.fromto[0,3])
        to_airport = Airport.find_by_code(weborder.fromto[3,3])
        fromAirport = from_airport.airport_name
        toAirport = to_airport.airport_name
        pass = ""
        for t in weborder.tickets
          pass << "/" if pass!=""
          pass << t.pass_name
        end
        rootStr << "," if rootStr!=""
        rootStr << "{"
        rootStr << "'id':'"+weborder.id.to_s+"'"
        rootStr << ",'pass':'"+pass+"'"
        rootStr << ",'order_no':'"+weborder.order_no.to_s+"'"
        rootStr << ",'pnr':'"+weborder.pnr+"'"
        rootStr << ",'trx_status':'"+weborder.trx_status.to_s+"'"
        rootStr << ",'status':'"+weborder.status.to_s+"'"
        rootStr << ",'air_no':'"+weborder.air_no+"'"
        rootStr << ",'from':'"+fromAirport[fromAirport.index(" ")+1..-1]+"'"
        rootStr << ",'to':'"+toAirport[toAirport.index(" ")+1..-1]+"'"
        rootStr << ",'position':'"+weborder.position+"'"
        rootStr << ",'fly_date':'"+weborder.fly_date.to_s+"'"
        rootStr << ",'fly_time':'"+weborder.fly_time+"'"
        rootStr << ",'fromto':'"+weborder.fromto+"'"
        rootStr << ",'created_at':'"+weborder.created_at.strftime("%Y-%m-%d %H:%M:%S")+"'"
        rootStr << "}"
      end
      logger.error rootStr
      #rootStr = weborders.to_json()
      jsonstr="{root:["+rootStr+"]}"
      render :text=>jsonstr, :layout=>false
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
    end
  end

  def getWebAgentOrdersBySearch 
    begin
      rootStr = ""
      web_user_id = session[:web_user_id]
      logger.error web_user_id
      web_user_id = 1 if web_user_id==nil
      webOrder = WebOrder.find(:all,:conditions=>["seller_id = ? AND trx_status = ?",web_user_id,Constants::WEB_ORDER_STATUS_ZFCG])
      jsonstr = jsonstr="{root:"+webOrder.to_json()+"}"
      logger.error jsonstr
      render :text=>jsonstr, :layout=>false
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
    end
  end

  def getWebReturnedOrders
    begin
      rootStr = ""
      web_user_id = session[:web_user_id]
      logger.error web_user_id
      weborders = WebOrder.find(:all,:conditions=>["web_user_id = ? AND status = ?",web_user_id,Constants::WEB_ORDER_STATUS_SQTP],:order=>"created_at desc")
      logger.error weborders.size
      jsonstr="{root:"+weborders.to_json(:include=>[:web_user,:from_airport,:to_airport])+"}"
      render :text=>jsonstr, :layout=>false
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
      
    end
  end
  
  #供应商待处理订单列表
  def getBookingOrders
    begin
      
      rootStr = ""
      web_user_id = session[:web_user_id]
      logger.error web_user_id
      if web_user_id
        #weborders = WebOrder.find(:all,:conditions=>["trx_status=? and seller_id=?",Constants::WEB_ORDER_STATUS_DDZF,web_user_id],:order=>"created_at desc")
        weborders = WebOrder.find(:all,:conditions=>["seller_id=?",web_user_id],:order=>"created_at desc")
        weborders = Array.new if weborders==nil
        logger.error weborders.length
        for weborder in weborders
          from_airport = Airport.find_by_code(weborder.fromto[0,3])
          to_airport = Airport.find_by_code(weborder.fromto[3,3])
          pass = ""
          for t in weborder.tickets
            pass << "/" if pass!=""
            pass << t.pass_name
          end
          
          rootStr << "," if rootStr!=""
          rootStr << "{"
          rootStr << "'id':'"+weborder.id.to_s+"'"
          rootStr << ",'pass':'"+pass+"'"
          rootStr << ",'order_no':'"+weborder.order_no.to_s+"'"
          rootStr << ",'pnr':'"+weborder.pnr+"'"
          rootStr << ",'trx_status':'"+weborder.trx_status+"'"
          rootStr << ",'status':'"+weborder.status+"'"
          rootStr << ",'air_no':'"+weborder.air_no+"'"
          rootStr << ",'from':'"+from_airport.airport_name+"'"
          rootStr << ",'to':'"+to_airport.airport_name+"'"
          rootStr << ",'position':'"+weborder.position+"'"
          rootStr << ",'fly_date':'"+weborder.fly_date.to_s+"'"
          rootStr << ",'fly_time':'"+weborder.fly_time+"'"
          rootStr << ",'created_at':'"+weborder.created_at.strftime("%Y-%m-%d %H:%M:%S")+"'"
          rootStr << "}"
          
        end
      end
      jsonstr="{root:["+rootStr+"]}"
      
      render :text=>jsonstr, :layout=>false
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
      
    end
  end
  
  def special_offer_release
    begin
      
      airports = Airport.find(:all,:order => "name_index")
      @airports_arraystr="["
      airports.each do |airport|
        @airports_arraystr = @airports_arraystr+"[\"#{airport.id}|#{airport.airport_name}\",\"#{airport.airport_name}\"],"
      end
      if @airports_arraystr.length>1
        @airports_arraystr = @airports_arraystr[0,@airports_arraystr.length-1]
      end
      @airports_arraystr = @airports_arraystr+"]"
      #logger.error @airports_arraystr
      logger.error params
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
      
    end
  end
  
  #为添加一条新的普通运价，作数据提取
  def common_price_release
    begin
      
      @airports_arraystr = getAirPortArrayString
      logger.error @airports_arraystr
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
      
    end
  end
  
  def add_special_offer_release
    
  end
  
  #增加一条新的普通运价
  def add_common_price_release
    begin
      webPriceRelease = WebPriceRelease.new
      webPriceRelease.price_type = Constants::COMMON_PRICE
      webPriceRelease.web_user_id = session[:web_user_id]
      webPriceRelease.airways_id = params[:airways_id]
      #webPriceRelease.airport_from = params[:airport_from]
      webPriceRelease.airport_from_id = params[:airport_from_id]
      webPriceRelease.flights = params[:flights]
      webPriceRelease.discount_from = params[:discount_from]
      webPriceRelease.discount_to = params[:discount_to]
      webPriceRelease.date_begin = params[:date_begin]
      webPriceRelease.date_end = params[:date_end]
      webPriceRelease.airports_to = params[:airports]
      webPriceRelease.rake_off = params[:rake_off]
      airportsArray = params[:airports].split(",")
      airportsStr = ""
      logger.error "AAAAAAAAAAAAAAAAAAAAAAAAAAA"
      airportHash = Airport.findByIDHash
      logger.error params[:airport_name]
      fromAirportCode = airportHash[webPriceRelease.airport_from_id].airport_code
      fromtoStr = ""
      0.upto(airportsArray.length-1) do |i|
        logger.error airportsArray[i]
        fromtoStr = fromtoStr + "#{fromAirportCode}#{airportHash[airportsArray[i].split("|")[0].to_i].airport_code}|"
        airportsArray[i] = airportsArray[i].split("|")[1]
        airportsStr = airportsStr + airportsArray[i] + "|"
      end
      logger.error fromtoStr
      webPriceRelease.from_to = fromtoStr
      webPriceRelease.airports_to_desc = airportsStr[0,airportsStr.length-1]
      webPriceRelease.ticket_payment_type = params[:ticket_payment_type]
      webPriceRelease.conversion_pnr = params[:conversion_pnr]
      webPriceRelease.is_released = params[:is_released]
      webPriceRelease.auto_release = params[:auto_release]
      webPriceRelease.save
      logger.error params
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
    end
    #"普通价格添加成功"
  end
  
  #编辑保存普通运价
  def save_common_price_release
    begin
      
      webPriceRelease = WebPriceRelease.find(params[:id],:include=>:airways)
      #webPriceRelease.price_type = Constants::COMMON_PRICE
      if params[:airways_id] !=nil && params[:airways_id] !=""
        webPriceRelease.airways_id = params[:airways_id]
      end
      if params[:airport_from] !=nil && params[:airport_from] !=""
        #webPriceRelease.airport_from = params[:airport_from]
        webPriceRelease.airport_from_id = params[:airport_from_id]
      end
      webPriceRelease.flights = params[:flights]
      webPriceRelease.discount_from = params[:discount_from]
      webPriceRelease.discount_to = params[:discount_to]
      webPriceRelease.date_begin = params[:date_begin]
      webPriceRelease.date_end = params[:date_end]
      webPriceRelease.airports_to = params[:airports]
      #城市对
      webPriceRelease.from_to = params[:airports]
      webPriceRelease.rake_off = params[:rake_off]
      airportsArray = params[:airports].split(",")
      airportsStr = ""
      airportHash = Airport.findByIDHash
      fromAirportCode = airportHash[webPriceRelease.airport_from_id].airport_code
      fromtoStr = ""
      0.upto(airportsArray.length-1) do |i|
        logger.error airportsArray[i].split("|")[0]
        fromtoStr = fromtoStr + "#{fromAirportCode}#{airportHash[airportsArray[i].split("|")[0].to_i].airport_code}|"
        airportsArray[i] = airportsArray[i].split("|")[1]
        airportsStr = airportsStr + airportsArray[i] + "|"
      end
      webPriceRelease.from_to = fromtoStr
      webPriceRelease.airports_to_desc = airportsStr[0,airportsStr.length-1]
      webPriceRelease.ticket_payment_type = params[:ticket_payment_type]
      webPriceRelease.conversion_pnr = params[:conversion_pnr]
      webPriceRelease.is_released = params[:is_released]
      webPriceRelease.auto_release = params[:auto_release]
      webPriceRelease.save
      #redirect_to :action => 'common_price_released_list' and return
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
    end
    #"普通价格添加成功"
  end
  
  #得到所有已经发布的非锁定普通运价
  def getCommonPriceReleased
    begin
      pageBegin =  params[:start]
      pageEnd =  params[:limit]
      strdelData = params[:delData]
      logger.error strdelData
      if strdelData!=nil
        delCommonPriceReleased(strdelData)
      end
      
      pageCustomers = WebPriceRelease.find(:all,:conditions=>["is_locked = 0 AND price_type = '#{Constants::COMMON_PRICE}' AND web_user_id = ?",session[:web_user_id]])
      commonPriceReleaseds = WebPriceRelease.find(:all,:conditions=>["is_locked = 0 AND price_type = '#{Constants::COMMON_PRICE}' AND web_user_id = ?",session[:web_user_id]],:limit =>pageBegin+","+pageEnd)
      
      jsonstr="{totalProperty:"+pageCustomers.length.to_s+",root:"+commonPriceReleaseds.to_json(:include=>[:airways,:airport_from])+"}"
      
      render :text=>jsonstr, :layout=>false
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
      
    end
  end
  
  #删除指定的运价
  def delCommonPriceReleased(strdelData)
    ids=""
    begin
      results = ActiveSupport::JSON.decode(strdelData)
      results.each do |result|
        ids << result["id"]+","
      end
      ids = ids[0,ids.length-1]
      if session[:user_type] == Constants::USER_TYPE_ADMIN
        WebPriceRelease.update_all("is_locked = 1","id in ("+ids+")")
      else
        WebPriceRelease.update_all("is_locked = 1",["id in ("+ids+") AND web_user_id = ?",session[:web_user_id]])
      end
      
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
    end
  end
  
  #为编辑一条指定的普通运价作数据提取准备。
  def edit_common_price_release
    begin
      
      @airports_selected_arraystr="["
      #管理员判断
      if session[:user_type] == Constants::USER_TYPE_ADMIN
        @webPriceRelease = WebPriceRelease.find(params[:id])
      else
        @webPriceRelease = WebPriceRelease.find(:first,:conditions=>["web_user_id = ?",session[:web_user_id]])
      end
      airportsToArray = @webPriceRelease.airports_to.split(',')
      ids=""
      airportsToArray.each do |airports_selected|
        @airports_selected_arraystr << "[\"#{airports_selected.split('|')[0]}|#{airports_selected.split('|')[1]}\",\"#{airports_selected.split('|')[1]}\"],"
        ids << "#{airports_selected.split('|')[0]},"
      end
      ids=ids[0,ids.length-1]
      @airports_selected_arraystr = @airports_selected_arraystr[0,@airports_selected_arraystr.length-1]+"]"
      logger.error "Selected Str....."
      logger.error @airports_selected_arraystr
      
      airports = Airport.find(:all,:conditions=>["id not in ("+ids+")"],:order => "name_index")
      @airports_arraystr="["
      airports.each do |airport|
        @airports_arraystr << "[\"#{airport.id}|#{airport.airport_name}\",\"#{airport.airport_name}\"],"
      end
      if @airports_arraystr.length>1
        @airports_arraystr = @airports_arraystr[0,@airports_arraystr.length-1]
      end
      @airports_arraystr << "]"      
      logger.error @webPriceRelease.rake_off
      logger.error @webPriceRelease.conversion_pnr
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
      
    end
  end
  
  def getCommonPriceByID
    begin
      #管理员判断
      if session[:user_type] == Constants::USER_TYPE_ADMIN
        webPriceRelease = WebPriceRelease.find(params[:id])
      else
        webPriceRelease = WebPriceRelease.find(params[:id],:conditions=>["web_user_id = ?",session[:web_user_id]])
      end
      jsonstr="{root:["+webPriceRelease.to_json(:include=>[:airways,:airport_name])+"]}"
      
      render :text=>jsonstr, :layout=>false
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
    end
  end
  
  #为添加一条新的特殊舱位，作数据提取
  def special_position_release
    begin
      @airports_arraystr = getAirPortArrayString
      #logger.error @airports_arraystr
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error") 
    end
  end
  
  #增加一条新的特殊舱位
  def add_special_position_release
    begin
      webPriceRelease = WebPriceRelease.new
      webPriceRelease.price_type = Constants::POSITION
      webPriceRelease.airways_id = params[:airways_id]
      webPriceRelease.flights = params[:flights]
      puts params[:airport_from_id]
      webPriceRelease.airport_from_id = params[:airport_from_id]
      webPriceRelease.discount_from = params[:discount_from]
      webPriceRelease.position = params[:position]
      webPriceRelease.date_begin = params[:date_begin]
      webPriceRelease.date_end = params[:date_end]
      webPriceRelease.airports_to = params[:airports]
      webPriceRelease.rake_off = params[:rake_off]
      airportsArray = params[:airports].split(",")
      airportsStr = ""
      0.upto(airportsArray.length-1) do |i|
        airportsArray[i] = airportsArray[i].split("|")[1]
        airportsStr = airportsStr + airportsArray[i] + "|"
      end
      webPriceRelease.airports_to_desc = airportsStr[0,airportsStr.length-1]
      webPriceRelease.ticket_payment_type = params[:ticket_payment_type]
      webPriceRelease.conversion_pnr = params[:conversion_pnr]
      webPriceRelease.is_released = params[:is_released]
      webPriceRelease.auto_release = params[:auto_release]
      webPriceRelease.save
    rescue Exception => e
      logger.error e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")      
    end
  end   
  #保存一条编辑后的特殊舱位
  def save_special_position_release
    begin
      logger.error params
      webPriceRelease = WebPriceRelease.find(params[:id])
      webPriceRelease.price_type = Constants::POSITION
      if params[:airways_id]!=nil && params[:airways_id]!=""
        webPriceRelease.airways_id = params[:airways_id]
      end
      webPriceRelease.flights = params[:flights]
      webPriceRelease.airport_from = params[:airport_from]
      webPriceRelease.discount_from = params[:discount_from]
      webPriceRelease.position = params[:position]
      webPriceRelease.date_begin = params[:date_begin]
      webPriceRelease.date_end = params[:date_end]
      webPriceRelease.airports_to = params[:airports]
      webPriceRelease.rake_off = params[:rake_off]
      airportsArray = params[:airports].split(",")
      airportsStr = ""
      0.upto(airportsArray.length-1) do |i|
        airportsArray[i] = airportsArray[i].split("|")[1]
        airportsStr = airportsStr + airportsArray[i] + "|"
      end
      webPriceRelease.airports_to_desc = airportsStr[0,airportsStr.length-1]
      webPriceRelease.ticket_payment_type = params[:ticket_payment_type]
      webPriceRelease.conversion_pnr = params[:conversion_pnr]
      webPriceRelease.is_released = params[:is_released]
      webPriceRelease.auto_release = params[:auto_release]
      webPriceRelease.save
    rescue Exception => e
      logger.error e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
    end
  end
  
  #为编辑一条指定的特殊舱位作数据提取准备。
  def edit_special_position_release
    begin
      
      @airports_selected_arraystr="["
      @webPriceRelease = WebPriceRelease.find(params[:id])
      airportsToArray = @webPriceRelease.airports_to.split(',')
      ids=""
      airportsToArray.each do |airports_selected|
        @airports_selected_arraystr << "[\"#{airports_selected.split('|')[0]}|#{airports_selected.split('|')[1]}\",\"#{airports_selected.split('|')[1]}\"],"
        ids << "#{airports_selected.split('|')[0]},"
      end
      ids=ids[0,ids.length-1]
      @airports_selected_arraystr = @airports_selected_arraystr[0,@airports_selected_arraystr.length-1]+"]"
      
      airports = Airport.find(:all,:conditions=>["id not in ("+ids+")"],:order => "name_index")
      @airports_arraystr="["
      airports.each do |airport|
        @airports_arraystr << "[\"#{airport.id}|#{airport.airport_name}\",\"#{airport.airport_name}\"],"
      end
      if @airports_arraystr.length>1
        @airports_arraystr = @airports_arraystr[0,@airports_arraystr.length-1]
      end
      @airports_arraystr << "]"      
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
      
    end
  end
  
  #得到所有已经发布的非锁定特殊舱位
  def getSpecialPositionReleased
    begin
      
      pageBegin =  params[:start]
      pageEnd =  params[:limit]
      strdelData = params[:delData]
      logger.error strdelData
      if strdelData!=nil
        delSpecialPositionReleased(strdelData)
      end
      pageCustomers = WebPriceRelease.find(:all,:conditions=>["is_locked = 0 AND price_type = '#{Constants::POSITION}'"])
      commonPriceReleaseds = WebPriceRelease.find(:all,:conditions=>["is_locked = 0 AND price_type = '#{Constants::POSITION}'"],:limit =>pageBegin+","+pageEnd)
      jsonstr="{totalProperty:"+pageCustomers.length.to_s+",root:"+commonPriceReleaseds.to_json(:include=>[:airways,:airport_from])+"}"
      
      render :text=>jsonstr, :layout=>false
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
      
    end
  end
  
  #删除指定的特殊舱位
  def delSpecialPositionReleased(strdelData)
    ids=""
    begin
      logger.error "delSpecialPositionReleased"
      results = ActiveSupport::JSON.decode(strdelData)
      results.each do |result|
        ids << result["id"]+","
      end
      ids = ids[0,ids.length-1]
      WebPriceRelease.update_all("is_locked = 1","id in ("+ids+")")
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
      
    end
  end
  
  def getSpecialPositionByID
    begin
      webPriceRelease = WebPriceRelease.find(params[:id])
      jsonstr="{root:["+webPriceRelease.to_json(:include=>[:airways])+"]}"
      
      render :text=>jsonstr, :layout=>false
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
      
    end
  end
  
  def getAirPortArrayString
    
    airports = Airport.find(:all,:order => "name_index")
    airports_arraystr="["
    airports.each do |airport|
      airports_arraystr = airports_arraystr+"[\"#{airport.id}|#{airport.airport_name}\",\"#{airport.airport_name}\"],"
    end
    if airports_arraystr.length>1
      airports_arraystr = airports_arraystr[0,airports_arraystr.length-1]
    end
    airports_arraystr = airports_arraystr+"]"
  end
  
  def yeepay_manager
    
    yeePays = PaymentPlatform.find(:all,:conditions=>["web_user_id = ?",session[:web_user_id]])
    if yeePays.length>0
      @payment_platform_id = yeePays[0].payment_platform_id
    else
      @payment_platform_id = ""
    end
  end
  
  def saveYeePayLoginName
    
    yeePays = PaymentPlatform.find(:all,:conditions=>["web_user_id = ?",session[:web_user_id]])
    if yeePays.length >0
      yeePays[0].payment_platform_id = params[:login_name]
      yeePays[0].save
    elsif eePay.length == 0
      yeePay = PaymentPlatform.new
      yeePay.name = "YeePay"
      yeePay.web_user_id = session[:web_user_id]
      yeePay.payment_platform_id = params[:login_name]
      yeePay.save
    end
    jsonstr="保存成功"
    render :text=>jsonstr, :layout=>false
  end

  def personReadyPay
    personOrderID = params[:person_order_id]
    begin
      logger.error personOrderID
      personOrder = Order.find(:first,:conditions=>["order_no = ?",personOrderID])
      if personOrder!=nil
        require 'net/http'
        p0_Cmd = Constants::YEEPAY_CMD_BUY
        p1_MerId = Constants::PLATFORM_MER_ID
        p2_Order = personOrderID
        p3_Amt = '0.01'
        #默认传RMB，可选
        p4_Cur = 'RMB'
        #商品编号,必选,只能为数字,不能为字母等.
        logger.error personOrder.pnr
        p5_Pid = personOrder.id
        p6_Url = "http://#{Constants::PLATFORM_URL}/ticket/getPersonPayResp"
        #商家扩展信息 可选 该字段的内容会在交易完成后原样返回
        p7_MP = personOrderID
        pa_Details ="Platform:#{Constants::PLATFORM_LOGIN_NAME}:#{p3_Amt}"
        #"twes9723.qdticket@yahoo.com.cnqdticket"就是商户商户密钥
        hmacstr = Rjb::import("DigestUtil").hmacSign("#{p0_Cmd}#{p1_MerId}#{p2_Order}#{p3_Amt}#{p4_Cur}#{p5_Pid}#{p6_Url}#{p7_MP}#{pa_Details}","twes9723.qdticket@yahoo.com.cnqdticket")
        http = Net::HTTP.new("#{Constants::YEEPAY_URL}", 80)
        prorateAction = Constants::YEEPAY_PRORATE_ACTION
        params = "p0_Cmd=#{p0_Cmd}&p1_MerId=#{p1_MerId}&p2_Order=#{p2_Order}&p3_Amt=#{p3_Amt}&p4_Cur=#{p4_Cur}&p5_Pid=#{p5_Pid}&p6_Url=#{p6_Url}&p7_MP=#{p7_MP}&pa_Details=#{pa_Details}&hmac=#{hmacstr}"
        logger.error prorateAction
        logger.error params
        resp, data = http.post(prorateAction,params)
        @content = resp.body
      else
        @content = "订单已经不存在."
      end
    rescue Exception => e
      CommonHelper.infoLogger(session[:web_user_id],request.env["REMOTE_ADDR"],"Ticket","personReadyPay",e,"error")
    end
  end

  #当个人支付成功后,会主动提交这个Action,从这儿,用户可以得到信息,处理一些订单的状态.也就是说,这其实是订单的回调方法.
  def getPersonPayResp
    begin
      logger.error params[:r1_Code]
      logger.error params
      if params[:r1_Code]=="1"
        personOrderNo = params[:r6_Order]
        personOrder = Order.find(:first,:conditions=>["order_no = ?",personOrderNo])
        personOrder.trx_id = params[:r2_TrxId]
        personOrder.trx_status = Constants::WEB_ORDER_STATUS_ZFCG
        personOrder.save
        @returnStatus=Constants::WEB_ORDER_STATUS_ZFCG
      else
        @returnStatus="支付失败，请从新支付"
      end
    rescue Exception => e
      CommonHelper.infoLogger(session[:web_user_id],request.env["REMOTE_ADDR"],"Ticket","getPersonPayResp",e,"error")
    end
  end
  
  def agentReadyPay
    begin
      #实现逻辑，首先查找机票供应和此订单中匹配的供应商。
      #得到此供应商的信息，在支付成功后准备改写票的状态。
      webOrderNo = params[:web_order_no]
      webOrder = WebOrder.find(:first,:conditions=>["order_no = ? AND web_user_id = ?",webOrderNo,session[:web_user_id]])
      #得到订单的城市对
      fromTo = params[:from_to]
      #根据城市对搜索价格表，发现符合城市对的价格记录。
      webPriceReleases = WebPriceRelease.find(:all,:conditions=>["from_to like ?","%#{fromTo}%"],:include=>[:web_user])
      #检查哪个用户的当天订单少，就把此订单给那个用户
      logger.error fromTo
      logger.error webPriceReleases.size
      if webPriceReleases.size >0
        minOrderAmount = 0
        selectedWebUserID = webPriceReleases[0].web_user.id
        selectedWebPriceReleaseID = webPriceReleases[0].id
        webPriceReleases.each do |webPriceRelease|
          if webPriceRelease.web_user.order_amount < minOrderAmount
            minOrderAmount = webPriceRelease.web_user.order_amount
            selectedWebUserID = webPriceRelease.web_user.id
            selectedWebPriceReleaseID = webPriceRelease.id
          end
        end 
        logger.error selectedWebUserID
        #查询到选中的供应商的支付平台的商户登录名，以便分账
        paymentPlatform = PaymentPlatform.find(:first,:conditions=>["web_user_id = ?",selectedWebUserID])
        #如果查不到记录,说明用户没有在系统中登记支付信息,不可以进行支付.
        if paymentPlatform != nil
          require 'net/http'
          p0_Cmd = Constants::YEEPAY_CMD_BUY
          p1_MerId = Constants::PLATFORM_MER_ID
          p2_Order = webOrder.order_no
          p3_Amt = '0.01'
          #默认传RMB，可选
          p4_Cur = 'RMB'
          #商品编号,必选
          p5_Pid = webOrder.id
          p6_Url = "http://#{Constants::PLATFORM_URL}/ticket/getAgentPayResp"
          #商家扩展信息 可选 该字段的内容会在交易完成后原样返回
          p7_MP = selectedWebUserID
          pa_Details ="Platform:#{Constants::PLATFORM_LOGIN_NAME}:0;Seller:hellotest0101b:0.01"
          hmacstr = Rjb::import("DigestUtil").hmacSign("#{p0_Cmd}#{p1_MerId}#{p2_Order}#{p3_Amt}#{p4_Cur}#{p5_Pid}#{p6_Url}#{p7_MP}#{pa_Details}","twes9723.qdticket@yahoo.com.cnqdticket")
          http = Net::HTTP.new("#{Constants::YEEPAY_URL}", 80)
          prorateAction = Constants::YEEPAY_PRORATE_ACTION
          params = "p0_Cmd=#{p0_Cmd}&p1_MerId=#{p1_MerId}&p2_Order=#{p2_Order}&p3_Amt=#{p3_Amt}&p4_Cur=#{p4_Cur}&p5_Pid=#{p5_Pid}&p6_Url=#{p6_Url}&p7_MP=#{p7_MP}&pa_Details=#{pa_Details}&hmac=#{hmacstr}"
          resp, data = http.post(prorateAction,params)
          @content = resp.body
        else
          @content = "您还没有正确的处理支付平台相关信息"
        end
      end
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
    end
  end
  
  #处理支付后的返回处理
  def getAgentPayResp
    begin
      if params[:r1_Code]=="1"
        webOrderNo = params[:r6_Order]
        webOrder = WebOrder.find(:first,:conditions=>["order_no = ?",webOrderNo])
        webOrder.trx_id = params[:r2_TrxId]
        webOrder.trx_status = Constants::WEB_ORDER_STATUS_ZFCG
        webOrder.status = Constants::WEB_ORDER_STATUS_ZZCL
        webOrder.platform_reserved_amt = Constants::PLATFORM_RESERVED_AMT
        webOrder.seller_id = params[:r8_MP]
        webOrder.save
        @returnStatus=Constants::WEB_ORDER_STATUS_ZFCG
      else
        @returnStatus="支付失败，请从新支付"
      end
    rescue Exception => e
      CommonHelper.infoLogger(session[:web_user_id],request.env["REMOTE_ADDR"],"Ticket","getPersonPayResp",e,"error")
    end
  end
  
  #当用户要付款时提交到此Action
  def ready_pay
    
    begin
      #实现逻辑，首先查找机票供应和此订单中匹配的供应商。
      #得到此供应商的信息，在支付成功后准备改写票的状态。
      #
      webOrderID = params[:web_order_id]
      webOrder = WebOrder.find(:first,:conditions=>["id = ?",webOrderID])
      #得到订单的城市对
      fromTo = params[:from_to]
      #根据城市对搜索价格表，发现符合城市对的价格记录。
      webPriceReleases = WebPriceRelease.find(:all,:conditions=>["from_to like ?","%#{fromTo}%"],:include=>[:web_user])
      #检查哪个用户的当天订单少，就把此订单给那个用户
      logger.error fromTo
      logger.error webPriceReleases.size
      if webPriceReleases.size >0
        
        minOrderAmount = 0
        selectedWebUserID = webPriceReleases[0].web_user.id
        selectedWebPriceReleaseID = webPriceReleases[0].id
        webPriceReleases.each do |webPriceRelease|
          if webPriceRelease.web_user.order_amount < minOrderAmount
            minOrderAmount = webPriceRelease.web_user.order_amount  
            selectedWebUserID = webPriceRelease.web_user.id
            selectedWebPriceReleaseID = webPriceRelease.id
          end
        end 
        #查询到选中的供应商的支付平台的商户登录名，以便分账
        paymentPlatform = PaymentPlatform.find(:first,:conditions=>["web_user_id = ?",selectedWebUserID])
        #如果查不到记录,说明用户没有在系统中登记支付信息,不可以进行支付.
        if paymentPlatform != nil
          logger.error paymentPlatform.name
          require 'net/http'
          p0_Cmd = Constants::YEEPAY_CMD_BUY
          p1_MerId = Constants::PLATFORM_MER_ID
          p2_Order = webOrder.order_no
          p3_Amt = '0.01'
          #默认传RMB，可选
          p4_Cur = 'RMB'
          #商品编号,必选
          p5_Pid = '0000001'
          p6_Url = "http://#{Constants::PLATFORM_URL}/ticket/getPayResp"
          #商家扩展信息 可选 该字段的内容会在交易完成后原样返回
          p7_MP = selectedWebUserID
          pa_Details ="Platform:#{Constants::PLATFORM_LOGIN_NAME}:0;Seller:hellotest0101b:0.01"
          hmacstr = Rjb::import("DigestUtil").hmacSign("#{p0_Cmd}#{p1_MerId}#{p2_Order}#{p3_Amt}#{p4_Cur}#{p5_Pid}#{p6_Url}#{p7_MP}#{pa_Details}","twes9723.qdticket@yahoo.com.cnqdticket")
          http = Net::HTTP.new("#{Constants::YEEPAY_URL}", 80)
          prorateAction = Constants::YEEPAY_PRORATE_ACTION
          params = "p0_Cmd=#{p0_Cmd}&p1_MerId=#{p1_MerId}&p2_Order=#{p2_Order}&p3_Amt=#{p3_Amt}&p4_Cur=#{p4_Cur}&p5_Pid=#{p5_Pid}&p6_Url=#{p6_Url}&p7_MP=#{p7_MP}&pa_Details=#{pa_Details}&hmac=#{hmacstr}"
          resp, data = http.post(prorateAction,params)
          #          resp.body.each do |item|
          #            logger.error "KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK"
          #            #logger.error i=i+1
          #            logger.error item
          #          end
          @content = resp.body
        else
          @content = "您还没有正确的处理支付平台相关信息"
        end
      end
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
    end
  end
  
  def getPayResp
    
    logger.error params[:r1_Code]
    logger.error params
    if params[:r1_Code]=="1"
      webOrderNo = params[:r6_Order]
      webOrder = WebOrder.find(:first,:conditions=>["order_no = ?",webOrderNo])
      webOrder.seller_id = params[:r8_MP]
      webOrder.trx_id = params[:r2_TrxId]
      webOrder.trx_status = Constants::WEB_ORDER_STATUS_ZFCG
      webOrder.save
      #在支付成功后，给相关供应商的交易量+1
      webUser = WebUser.find(params[:r8_MP])
      webUser.order_amount = webUser.order_amount + 1
      webUser.save
      @returnStatus=Constants::WEB_ORDER_STATUS_ZFCG
    else
      @returnStatus="支付失败，请从新支付"
    end
  end
  
  #退票管理
  def returned_order
    
  end


  #得到所有航空公司的折扣表
  def getAllPriceDiscount
    begin
      airwaysPriceDiscount = Airways.find(:all,:include=>[:positions])
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
    end
  end
  
  def getPriceDiscount(airways_code)
    begin
      airwaysPriceDiscount = Airways.find(:first,:conditions=>["airways_code = ?",airways_code],:include=>[:positions])
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
    end
  end
  
  def getFlightQueryResult
    begin
      logger.error ">>>>>>>>>>>>>>> getFlightQueryResult >>>>>>>>>>>>>>>>"
      fromTo = params[:fromto]
      date = params[:date]
      seat = params[:person_number]
      logger.error fromTo
      logger.error date
      logger.error seat
      seat = 1 if seat==nil
      #转化日期格式
      date_cmd = CommonHelper.getCmdDateFormat(date)
      
      cmd = "AVH/"+fromTo+"/"+date_cmd
      #if airways_code && airways_code!=""
      #  cmd << "/"+airways_code
      #end
      #直达
      cmd << "/D"
      rubySocket = SocketHelper.getSocket("tao22070","tao22070")
      queryResultStr=""
      if rubySocket
        queryResultStr = CommonHelper.getAvhResult(rubySocket,cmd,date_cmd)
        if rubySocket
          rubySocket.close
          rubySocket=nil
        end
      end
      #取得机场的名字
      fromAirport = nil
      toAirport = nil    
      fromToAirports = Airport.find(:all,:conditions=>["airport_code=? OR airport_code=?",fromTo[0,3],fromTo[3,3]])
      fromToAirports.each do |fromToAirport|
        if fromToAirport.airport_code == fromTo[0,3]
          #fromAirport=fromToAirport.airport_name[2..-1]
          fromAirport=fromToAirport.airport_name[fromToAirport.airport_name.index(" ",3)..-1]
        else
          #toAirport=fromToAirport.airport_name[2..-1]
          toAirport=fromToAirport.airport_name[fromToAirport.airport_name.index(" ",3)..-1]
        end
      end
      
      #queryResultStr = "*CZ5195  DS# F8 YA TA HA MA GA SQ LQ EQ VQ  TAOPEK 0735   0850   320 0 S  E  -----MU5195      XQ UQ BA                                             T2   <br> MU5195  DS# F8 A5 YA KA BA EA HA LA MA NQ  TAOPEK 0735   0850   320 0 S  E  -----RQ SQ VQ TQ WQ XQ GQ QA U5 I5 ZQ                     T2   <br>*CA4651  DS# YA BA MA HA KA LA QS GS SA NS  TAOPEK 0740   0855   733 0^S  E  -----SC4651      VS US WS TS ES PS   <br> MU5197  DS# F7 A5 YA KA BA EA HA LA MA NQ  TAOPEK 0740   0840   320 0 S  E  -----RQ SQ VQ TQ WQ XQ GQ Q5 U5 I5 ZQ                     T2   <br> SC4651  DS# YA BA MA HA KA LA QS GS SA XS  TAOPEK 0740   0855   733 0^S  E  -----NS VS US WS ZS RS TS ES <br>*CZ5197  DS# F7 YA TA HA MA GA SQ LQ EQ VQ  TAOPEK 0740   0840   320 0 S  E  -----MU5197      XQ UQ B5                                             T2   <br>*SC1572  DS# FL AL Y7 BS MS HS KS LS QS GS  TAOPEK 0955   1110   733 0^S  E  -----CA1572      S2 NS VS US WS TS ES-----<br>CA1572  DS# FL AL Y7 BS MS HS KS LS QS GS  TAOPEK 0955   1110   733 0^S  E  -----S2 NS VS US WS TS ES<br>*UA4414  DS* FL PA YA BA EA ML UA HL QL VL  TAOPEK 0955   1110   733 0 S  E  -----CA1572      WL AL SL TL KL LA GA                                 3<br> MU744  AS#C4 J4 D4 YA KA BA EA HA LQ MQ  TAOPEK 1135   1255   737 0    E  -----NQ RQ SQ VQ TQ WQ XQ GQ QA U5 I5 ZS                  T2   <br>*SC1560  DS# F4 AS CA DS RS YA BA MS HS KS  TAOPEK 1140   1250   763 0^S  E  -----CA1560      LS QS GS SA NS VS US WA TS ES                        T3   <br>*UA4400  DS* FA PA CA DA ZA YA BA EA ML UA  TAOPEK 1140   1250   763 0    E  -----CA1560      HL QL VL WL AL SL TL KL LL GA                        3<br> CA1560  DS# F4 AS CA DS RS YA BA MS HS KS  TAOPEK 1140   1250   763 0^S  E  -----LS QS GS SA NS VS US WA TS ES                        T3   <br>*UA4400  DS* FA PA YA BA EA ML UA HL QL VL  TAOPEK 1140   1250   EQV 0 L  E  -----CA1560      WL AL SL TL KL LL GA                                 3-----<br>*UA4400  DS* FA PA CA DA ZA YA BA EA ML UA  TAOPEK 1140   1250   763 0    E  -----CA1560      HL QL VL WL AL SL TL KL LL GA                        3<br> CA1560  DS# F4 AS CA DS RS YA BA MS HS KS  TAOPEK 1140   1250   763 0^S  E  -----LS QS GS SA NS VS US WA TS ES                        T3   <br>*CA4653  DS# YA BA MA H8 KS LS QS GS SA NS  TAOPEK 1145   1310   733 0^S  E  -----SC4653      VS US WS TS ES PS   <br> SC4653  DS# YA BA MA H8 KS LS QS GS SA XS  TAOPEK 1145   1310   733 0^S  E  -----NS VS US WS ZS RS TS ES <br> CA1570  DS# FL AL YA BS MS HS KS LS QS GS  TAOPEK 1540   1700   738 0^S  E  -----SA NS VS US WS TS ES<br>*SC1570  DS# FL AL OL YA BS MS HS KS LS QS  TAOPEK 1540   1700   738 0^S  E  -----CA1570      GS SA XS NS VS US WS TS ES  <br>*CZ5193  DS# F3 YA TA HA MQ GQ SQ LQ EQ VQ  TAOPEK 1610   1715   320 0 S  E  -----MU5193      XQ UQ B8                                             T2   -----<br>MU5193  DS# F3 A3 YA KA BA EA HA LQ MQ NQ  TAOPEK 1610   1715   320 0 S  E  -----RQ SQ VQ TQ WQ XQ GQ Q8 UQ I5 ZQ                     T2   <br> SC4655  DS# F8 AS OS YA BA MA HA K8 LS QS  TAOPEK 1825   1940   738 0^S  E  -----GS SS XS NS VS US WS ZS RS TS ES<br>*CA4655  DS# YA BA MA HA K8 LS QS GS SS NS  TAOPEK 1825   1940   738 0^S  E  -----SC4655      VS US WS TS ES PS   <br> SC4657  DS# YA BA MA HA KA LA QS GS SS XS  TAOPEK 1845   2000   738 0^S  E  -----NS VS US WS ZS RS TS ES <br>*CA4657  DS# YA BA MA HA KA LA QS GS SS NS  TAOPEK 1845   2000   738 0^S  E  -----SC4657      VS US WS TS ES PS   <br> CA1576  DS# F6 AS YA BS MS HS KS LS QS GS  TAOPEK 2050   2205   733 0^S  E  -----SA NS VS US WA TS ES<br>*SC1576  DS# F6 AS OS YA BS MS HS KS LS QS  TAOPEK 2050   2205   733 0^S  E  -----CA1576      GS SA XS NS VS US WA TS ES  -----<br>CA1526  DS# F7 AS YA BS MS HS KS LS QS GS  TAOPEK 2230   2350   319 0^S  E  -----SA NS VS US WS TS ES                                 T3   <br>*FM1526  DS# F7 YA BS LS MS TS HS VS        TAOPEK 2230   2350   319 0^S  E  -----CA1526                                                           T3   <br>*SC1526  DS# F7 AS O1 YA BS MS HS KS LS QS  TAOPEK 2230   2350   319 0^S  E  -----CA1526      GS SA XS NS VS US WS TS ES                           T3   -----<br>".squish
      jsonStr = "["
      while(queryResultStr.index("<br>"))
        
        subQueryResultStr = queryResultStr[0,queryResultStr.index("<br>")].strip
        #logger.error "-----------------------------"
        #logger.error subQueryResultStr
        queryResultStr = queryResultStr[queryResultStr.index("<br>")+4..-1]
        
        offset = subQueryResultStr.index(" ")
        
        air_no = subQueryResultStr[0,offset].strip
        #logger.error air_no
        #暂时我们排除掉带*的航班，不进行处理,同时在翻页时有重复航班，也要过滤掉。
        if air_no[0,1]!="*" && jsonStr.index(air_no)==nil
          #确实位移，为5位数的航班号准备
          if subQueryResultStr.index("S#")
            offset = subQueryResultStr.index("S#")+3
          elsif subQueryResultStr.index("S*")
            offset = subQueryResultStr.index("S*")+3
          else
            offset += 5
          end
          fromtoNum = 0
          fromtoStr = ""
          if subQueryResultStr.index(" "+fromTo+" ")
            fromtoStr = fromTo
            fromtoNum = subQueryResultStr.index(" "+fromTo+" ")
          elsif fromTo.index("SHA")
            fromtoStr = fromTo.gsub(/SHA/,"PVG")
            fromtoNum = subQueryResultStr.index(" "+fromTo.gsub(/SHA/,"PVG")+" ")
          end
          if fromtoNum>offset && fromtoStr!=""
            #logger.error "fromAirport="+fromAirport
            #logger.error "toAirport="+toAirport
            fly_time = subQueryResultStr[8+fromtoNum,2]+":"+subQueryResultStr[10+fromtoNum,2]
            #logger.error "fly_time="+fly_time
            arr_time = subQueryResultStr[13+fromtoNum,2]+":"+subQueryResultStr[15+fromtoNum,2]
            #logger.error "arr_time="+arr_time
            plane_type = subQueryResultStr[18+fromtoNum,4].strip
            #logger.error "plane_type="+plane_type
            positionStr = " "+subQueryResultStr[offset..fromtoNum].strip
            #logger.error "positionStr="+positionStr
            #余下部分
            if subQueryResultStr.index("-----")
              positionStr2 = subQueryResultStr[subQueryResultStr.index("-----")+5..-1].strip
              if positionStr2.index(" ") && positionStr2.index(" ")==2
                positionStr2 = positionStr2[0,positionStr2.index("--")].strip if positionStr2.index("--")
                #statusOther = statusOther[0,statusOther.index("-----")] if statusOther.index("-----")
                positionStr << " " + positionStr2
              end
            end
            #logger.error "positionStr="+positionStr
            
            #得到航空公司舱位表，由低价舱到高价舱
            airways_code = air_no[0,2]
            airway = Airways.find_by_code(airways_code)
            positionArr = CommonHelper.getDiscountArray(airways_code)
            for position in positionArr
              position_code = position.position_code
              discount = position.discount
              #logger.error "position_code="+position_code
              if positionStr.index(" "+position_code)
                k = positionStr[positionStr.index(" "+position_code)+1,2]
                #logger.error "--"+k
                if k[1,1]=="A" || (k[1,1].to_i>=seat.to_i && k[1,1].to_i<=9)
                  
                  positionPrice = PositionPrice.find(:first,:conditions=>["is_locked<>1 and airways_code=? and position=? and fromto=?",airways_code,position_code,fromTo])
                  #logger.error positionPrice
                  if positionPrice && positionPrice.price
                    price = positionPrice.price.to_s
                    #logger.error "price="+price
                    jsonStr << "," if jsonStr!="["
                    jsonStr << "{\"air_no\":\"#{air_no}\",\"plane_type\":\"#{plane_type}\",\"fly_time\":\"#{fly_time}\",\"arr_time\":\"#{arr_time}\",\"airport\":\"#{fromAirport} - #{toAirport}\","
                    jsonStr << "\"discount\":#{discount},\"airways_name\":\"<img src='\/images\/airways\/#{airways_code}.gif' width=15 height=15\/>#{airway.airways_name}\",\"position\":\"#{position_code}\""
                                    
                    jsonStr << ",\"price\":#{price}"
                    jsonStr << "}"
                    #当已经处理了最低价时,跳出循环
                    break
                  end
                end
              end
            end
          end
        end
      end
      jsonStr << "]"
      jsonStr="{root:"+jsonStr+"}"
      #logger.error jsonStr
      render :text=>jsonStr, :layout=>false
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
    end
  end

  def addPersonWebOrder
    begin
      
      logger.error ">>>>>>>>>>>> addPersonWebOrder >>>>>>>>>>>>>>>>"
      logger.error session[:web_user_id]
      
      @person_number = params[:person_number]
      @trip_type = params[:trip_type]
      @air_no = params[:air_no]
      @fromto = params[:fromto]
      @fromto_desc = params[:fromto_desc].squish
      @position = params[:position]
      @price = params[:price]
      @fly_date = params[:fly_date]
      @fly_time = params[:fly_time]
      @arr_time = params[:arr_time]
      @plane_type = params[:plane_type]
      
      logger.error @person_number
      logger.error @trip_type
      logger.error @air_no
      logger.error @fromto
      logger.error @position
      logger.error @price
      logger.error @fly_date
      logger.error @fly_time
      logger.error @arr_time
      logger.error @plane_type
      
      if @trip_type == "round" || @trip_type == "joint"
        @air_no2 = params[:air_no2]
        @fromto2 = params[:fromto2]
        @fromto_desc2 = params[:fromto_desc2].squish
        @position2 = params[:position2]
        @price2 = params[:price2]
        @fly_date2 = params[:fly_date2]
        @fly_time2 = params[:fly_time2]
        @arr_time2 = params[:arr_time2]
        @plane_type2 = params[:plane_type2]
       
        logger.error @air_no2
        logger.error @fromto2
        logger.error @position2
        logger.error @price2
        logger.error @fly_date2
        logger.error @fly_time2
        logger.error @arr_time2
        logger.error @plane_type2
      end

    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
    end
  end

  def savePersonWebOrder
    begin
      person_number = params[:person_number]
      seat = params[:seat_number]
      web_user_id = session[:web_user_id]
      trip_type = params[:tripType]
      airNo = params[:air_no]
      fromto = params[:fromto]
      position = params[:position]
      price = params[:price]
      fly_date = params[:fly_date]
      fly_time = params[:fly_time]
      arr_time = params[:arr_time]
      plane_type = params[:plane_type]
      
      logger.error ">>>>>> savePersonWebOrder >>>>>>>>"
      logger.error person_number
      logger.error web_user_id
      logger.error trip_type
      logger.error airNo
      logger.error fromto
      logger.error position
      logger.error price
      logger.error fly_date
      logger.error fly_time
      logger.error arr_time
      logger.error plane_type

      if trip_type=="round" || trip_type=="joint"
        airNo2 = params[:air_no2]
        fromto2 = params[:fromto2]
        position2 = params[:position2]
        price2 = params[:price2]
        fly_date2 = params[:fly_date2]
        fly_time2 = params[:fly_time2]
        arr_time2 = params[:arr_time2]
        plane_type2 = params[:plane_type2]
        logger.error "====flight2===="
        logger.error airNo2
        logger.error fromto2
        logger.error position2
        logger.error price2
        logger.error fly_date2
        logger.error fly_time2
        logger.error arr_time2
        logger.error plane_type2
      end
      
      #form中的参数
      #order_request = params[:order_request]
      status = Constants::TICKET_STATUS_WQR
      order_request = ""
      fix_type = "HK"
      curTime = Time.new
      today = curTime.strftime("%Y-%m-%d").to_s
      toHour = curTime.strftime("%H").to_i+2
      toMin = curTime.strftime("%M").to_s
      if toHour>=24
        tktl_date = (today.to_date+1).to_date.to_s
        tktl_time = "00"+toMin if toHour==24
        tktl_time = "01"+toMin if toHour==25
        tktl_time = "02"+toMin if toHour==26
      else
        tktl_date = today.to_s
        if toHour<10
          tktl_time = "0"+toHour.to_s+toMin
        else
          tktl_time = toHour.to_s+toMin
        end
      end
      tktl_time = "2300" if tktl_time==nil
      affirm_date = tktl_date
      logger.error "时限===="
      logger.error tktl_date
      logger.error tktl_time
      link_man = params[:link_man]
      link_tel = params[:link_tel]
      send_address = params[:send_address]
      send_date = params[:send_date]
      send_time = params[:send_time]
      send_request = params[:send_request]
      jj_address = params[:jj_address]
      jj_time = params[:jj_time]
      jj_request = params[:jj_request]
      
      logger.error "====form===="
      logger.error tktl_date
      logger.error tktl_time
      logger.error link_man
      logger.error link_tel
      logger.error send_address
      logger.error send_date
      logger.error send_time
      logger.error send_request
      logger.error jj_address
      logger.error jj_time
      logger.error jj_request
      
      fly_date_cmd = CommonHelper.getCmdDateFormat(fly_date)
      logger.error fly_date_cmd
      if fly_date2
        fly_date_cmd2 = CommonHelper.getCmdDateFormat(fly_date2)
        logger.error fly_date_cmd2
      end
      tktl_date_cmd = CommonHelper.getCmdDateFormat(tktl_date)
      logger.error tktl_date_cmd

      ################### 循环获取乘客姓名 获取拼音并转化编码 ######################
      logger.error "循环获取乘客姓名 获取拼音并转化编码"
      nameString = ""
      cardString = ""
      humanTypeString = ""
      insuranceString = ""
      birthdayString = ""
      nmStr = "nm" #穿入名字命令
      cardStr = "" #穿入证件号命令
      cardStr2 = ""
      babyStr = "" #婴儿命令
      babyStr2 = ""
      
      i_number = 0
      baby_no = 0
      seat_cmd = seat.to_i
      for i in 1..seat.to_i
        logger.error "====seat for=="+i.to_s+"===="
        passenger_name = params["pessenger_name_"+i.to_s]
        human_type = params["age_type_"+i.to_s]
        birthday = params["birthday_"+i.to_s]
        id_card = params["card_"+i.to_s]
        id_card = "" if id_card==nil
        insurance_number = params["insurance_"+i.to_s]
        
        logger.error passenger_name
        logger.error human_type
        logger.error birthday
        logger.error id_card
        logger.error insurance_number
        
        i_number += insurance_number.to_i
        nameString << "," if i>1
        nameString << passenger_name
        birthdayString << "," if i>1
        birthdayString << birthday
        cardString << "," if i>1
        cardString << id_card
        humanTypeString << "," if i>1
        humanTypeString << human_type
        insuranceString << "," if i>1
        insuranceString << insurance_number.to_s
        
        logger.error nameString
        logger.error birthdayString
        logger.error cardString
        logger.error humanTypeString
        logger.error insuranceString
        
        pass_name = SocketHelper.getTransChineseName(passenger_name)
        if human_type=="婴儿"
          #if birthday.to_date>(today.to_date-365)
          #婴儿
          if passenger_name.index("/")
            name_pinyin = passenger_name
          else
            xing = SocketHelper.getPinYin(passenger_name[0,3])
            ming = SocketHelper.getPinYin(passenger_name[3..-1])
            name_pinyin = xing+"/"+ming
          end
          seat_cmd -= 1 #婴儿不算座位
          baby_no += 1
          baby_date_cmd = CommonHelper.getCmdDateFormat(birthday)
          babyStr << Constants::SEPARATE_KEY
          babyStr << "XN:IN/"+pass_name+"INF("+baby_date_cmd[2,5]+")/P"+baby_no.to_s
          babyStr << Constants::SEPARATE_KEY
          babyStr << "SSR INFT "+airNo[0,2]+" NN1 "+fromto+" "+airNo[2..-1]+" "+position+fly_date_cmd+" "+name_pinyin+" "+baby_date_cmd+"/P"+baby_no.to_s
          if airNo2 && airNo2!=""
            if airNo[0,2]==airNo2[0,2]
              babyStr << Constants::SEPARATE_KEY
              babyStr << "SSR INFT "+airNo2[0,2]+" NN1 "+fromto2+" "+airNo2[2..-1]+" "+position2+fly_date_cmd2+" "+name_pinyin+" "+baby_date_cmd+"/P"+baby_no.to_s
            end
            babyStr2 << Constants::SEPARATE_KEY
            babyStr2 << "XN:IN/"+pass_name+"INF("+baby_date_cmd[2,5]+")/P"+baby_no.to_s
            babyStr2 << Constants::SEPARATE_KEY
            babyStr2 << "SSR INFT "+airNo2[0,2]+" NN1 "+fromto2+" "+airNo2[2..-1]+" "+position2+fly_date_cmd2+" "+name_pinyin+" "+baby_date_cmd+"/P"+baby_no.to_s
          end
        elsif human_type=="儿童"
          #儿童
          nmStr << "1"+pass_name
          #pass_name << "(UM4)"  #UM指无人陪伴的儿童；4指年龄
          chd_date_cmd = CommonHelper.getCmdDateFormat(birthday)
          nmStr << "CHD("+chd_date_cmd+")"
        else
          #成人
          nmStr << "1"+pass_name
          if seat.to_i==1
            if id_card && id_card!=""
              cardStr << Constants::SEPARATE_KEY
              cardStr << "SSR FOID "+airNo[0,2]+" HK/NI"+id_card
              if airNo2 && airNo2!=""
                cardStr2 << Constants::SEPARATE_KEY
                cardStr2 << "SSR FOID "+airNo2[0,2]+" HK/NI"+id_card
              end
            end
          else
            if id_card && id_card!=""
              card_no = i-baby_no #减去婴儿的数量才是正确的编号
              cardStr << Constants::SEPARATE_KEY
              cardStr << "SSR FOID "+airNo[0,2]+" HK/NI"+id_card+"/P"+card_no.to_s
              if airNo2 && airNo2!=""
                cardStr2 << Constants::SEPARATE_KEY
                cardStr2 << "SSR FOID "+airNo2[0,2]+" HK/NI"+id_card+"/P"+card_no.to_s
              end
            end
          end
        end
        logger.error ">>end>>"
      end
      logger.error "循环结束,结果如下====="
      logger.error "nmStr="+nmStr
      logger.error "cardStr="+cardStr
      logger.error "cardStr2="+cardStr2
      logger.error "babyStr="+babyStr
      logger.error "babyStr2="+babyStr2
      logger.error nameString
      logger.error cardString
      logger.error birthdayString
      logger.error humanTypeString
      logger.error insuranceString
      logger.error "<<<<<< 拼命令 <<<<<<"
      
      result = "订票失败"
      #定航段的SS命令后面的所有命令
      tail_cmd = ""
      tail_cmd << Constants::SEPARATE_KEY
      tail_cmd << nmStr
      tail_cmd << Constants::SEPARATE_KEY
      tail_cmd << "ct/81115555-000" #+session[:employee_no]
      if tktl_date_cmd && tktl_date_cmd!=""
        tail_cmd << Constants::SEPARATE_KEY
        tail_cmd << "tktl/"+tktl_time+"/"+tktl_date_cmd+"/tao220"
      end
      tail_cmd2 = ""
      if airNo2 && airNo2!=""
        tail_cmd2 << tail_cmd
        if cardStr2!=""
          tail_cmd2 << cardStr2
        end
        if babyStr2!=""
          tail_cmd2 << babyStr2
        end
        tail_cmd2 << Constants::SEPARATE_KEY
        tail_cmd2 << "@"
      end
      if cardStr!=""
        tail_cmd << cardStr
      end
      if babyStr!=""
        tail_cmd << babyStr
      end
      tail_cmd << Constants::SEPARATE_KEY
      tail_cmd << "@"

      logger.error tail_cmd
      
      if airNo2
        if airNo2[0,2]==airNo[0,2]
          logger.error "-------------往返或者联程是同一家航空公司的航班--------------------"
          #往返或者联程是同一家航空公司的航班
          cmd = "ss"+airNo+position+fly_date_cmd+fromto+seat_cmd.to_s
          cmd << Constants::SEPARATE_KEY
          cmd << "ss"+airNo2+position2+fly_date_cmd2+fromto2+seat_cmd.to_s
          
          #如果中转是在上海的两个机场之间 则需要转换机场命令
          if fromto[3,3]=="SHA" && fromto2[0,3]=="PVG"
            cmd << Constants::SEPARATE_KEY
            cmd << "sa SHAPVG"
          elsif fromto[3,3]=="PVG" && fromto2[0,3]=="PVG"
            cmd << Constants::SEPARATE_KEY
            cmd << "sa PVGSHA"
          end
          cmd << tail_cmd
          logger.error "----订票命令="+cmd
          rubySocket = SocketHelper.getSocket(session[:eterm_name],session[:eterm_pswd])
          if rubySocket
            res = SocketHelper.getCR(rubySocket,"i",false)
            logger.error "----"+res
            restr = SocketHelper.getCR(rubySocket,cmd,true)
            if rubySocket
              rubySocket.close
              rubySocket=nil
            end
            logger.error "----订票结果="+restr
            restr = CommonHelper.getPnrFromSocketResult(restr,airNo,airNo2,nil,nil)
          else
            restr = ""
          end
          if restr.index(" ") && restr.index(" ")==5
            pnr = restr[0,5]
            if restr.rindex(" ")>=8
              status_type = restr[6,2]
              status_type2 = restr[9,2]
            else
              status_type = restr[6,2]
              status_type2 = fix_type
            end
          else
            pnr = ""
            status_type = ""
            status_type2 = ""
          end
          logger.error "----提取PNR="+pnr+"----"
          if pnr && pnr.length==5
            #保存订单、票、客户积分返利、送票地址等 设置成一个事务
            if CommonHelper.saveMulOrderTicket2(1,session[:web_user_id],1,pnr,link_man,link_tel,send_address,send_date,send_time,send_request,
                order_request,jj_address,jj_time,jj_request,tktl_date,tktl_time,affirm_date,fix_type,"web订票","",
                nameString,humanTypeString,cardString,birthdayString,insuranceString,status,trip_type,seat,i_number,
                airNo,fromto,fly_date,fly_time,arr_time,plane_type,position,status_type,price,
                airNo2,fromto2,fly_date2,fly_time2,arr_time2,plane_type2,position2,status_type2,price2)
                
              result = "订票成功,PNR:#{pnr}"
            else
              result = "PNR已经生成,但是保存订单信息失败,请务必妥善保存PNR:<font color=red>#{pnr}</font>,可利用导入功能将该pnr信息导入系统"
            end
          else
            result = "订票失败,失败原因为:"
            if restr.index("timeout")
              result << "连接服务器超时"
            elsif restr.index("socket is null") || restr==""
              result << "访问服务器失败"
            else
              result << restr
            end
          end
        else
          #不是同一家航空公司的航班,只能作为两个订单
          logger.error "-------------不是同一家航空公司的航班,只能作为两个订单-------------"
          cmd = "ss"+airNo+position+fly_date_cmd+fromto+seat_cmd.to_s
          cmd << tail_cmd
          logger.error "----订票命令="+cmd
          rubySocket = SocketHelper.getSocket(session[:eterm_name],session[:eterm_pswd])
          res = SocketHelper.getCR(rubySocket,"i",false)
          logger.error "----"+res
          restr = SocketHelper.getCR(rubySocket,cmd,true)
          if rubySocket
            rubySocket.close
            rubySocket=nil
          end
          logger.error "----订票结果="+restr
          restr = CommonHelper.getPnrFromSocketResult(restr,airNo,nil,nil,nil)
          if restr.index(" ") && restr.index(" ")==5
            pnr = restr[0,5]
            status_type = restr[6,2]
          else
            pnr = ""
            status_type = ""
          end
          logger.error "----获取PNR="+pnr+"----"
          if pnr && pnr.length==5
            #保存订单、票、客户积分返利、送票地址等 设置成一个事务
            if CommonHelper.saveMulOrderTicket(1,session[:web_user_id],1,pnr,link_man,link_tel,send_address,send_date,send_time,send_request,
                order_request,jj_address,jj_time,jj_request,tktl_date,tktl_time,affirm_date,fix_type,"web订票","",
                nameString,humanTypeString,cardString,birthdayString,insuranceString,status,trip_type,seat,i_number,
                airNo,fromto,fly_date,fly_time,arr_time,plane_type,position,status_type,price)
              
              result = "订票成功,PNR:#{pnr}"
            else
              result = "第一个航班#{airNo}的PNR已经生成,但是保存订单信息失败,请务必妥善保存PNR:<font color=red>#{pnr}</font>,可利用导入功能将该pnr信息导入系统"
            end
          else
            result = "第一个航班#{airNo}订票失败,失败原因为:"
            if restr.index("timeout")
              result << "连接服务器超时"
            elsif restr.index("socket is null") || restr==""
              result << "访问服务器失败"
            else
              result << restr
            end
          end
          
          if result.index("成功")
            result = "第一个航班#{airNo}订票成功,PNR:#{pnr},订单已保存至系统中<br>"
            logger.error "-------------第二个订单-------------"
            if fix_type=="HK"
              cmd = "ss"+airNo2+position2+fly_date_cmd2+fromto2+seat_cmd.to_s
            else
              cmd = "ss"+airNo2+position2+fly_date_cmd2+fromto2+fix_type+seat_cmd.to_s
            end
            cmd << tail_cmd2
            logger.error "----订票命令="+cmd
            rubySocket = SocketHelper.getSocket(session[:eterm_name],session[:eterm_pswd])
            res = SocketHelper.getCR(rubySocket,"i",false)
            logger.error "----"+res
            restr2 = SocketHelper.getCR(rubySocket,cmd,true)
            if rubySocket
              rubySocket.close
              rubySocket=nil
            end
            logger.error "----订票结果="+restr2
            restr2 = CommonHelper.getPnrFromSocketResult(restr2,airNo2,nil,nil,nil)
            if restr2.index(" ") && restr2.index(" ")==5
              pnr2 = restr2[0,5]
              status_type2 = restr2[6,2]
            else
              pnr2 = ""
              status_type2 = ""
            end
            logger.error "----获取PNR="+pnr2+"----"
            if pnr2 && pnr2.length==5
              #保存订单、票、客户积分返利、送票地址等 设置成一个事务
              if CommonHelper.saveMulOrderTicket(1,session[:web_user_id],1,pnr2,link_man,link_tel,send_address,send_date,send_time,send_request,
                  order_request,jj_address,jj_time,jj_request,tktl_date,tktl_time,affirm_date,fix_type,"web订票","",
                  nameString,humanTypeString,cardString,birthdayString,insuranceString,status,trip_type,seat,i_number,
                  airNo2,fromto2,fly_date2,fly_time2,arr_time2,plane_type2,position2,status_type2,price2)
                
                result = "订票成功,由于两个航空公司不同,形成两个订单已保存至系统中,PNR分别是#{pnr} #{pnr2}"
              else
                result << "第二个航班#{airNo2}订票PNR已经生成,但是保存订单信息失败,请务必妥善保存PNR:<font color=red>#{pnr2}</font>,可利用导入功能将该pnr信息导入系统"
              end
            else
              result << "但是第二个航班#{airNo2}订票失败,失败原因为:"
              if restr2.index("timeout")
                result << "连接服务器超时"
              elsif restr2.index("socket is null") || restr2==""
                result << "访问服务器失败"
              else
                result << restr2
              end
            end
          end
        end
      else
        logger.error "-------------单程多人订单-------------"
        cmd = "ss"+airNo+position+fly_date_cmd+fromto+seat_cmd.to_s
        cmd << tail_cmd
        logger.error cmd
        logger.error "----订票命令="+cmd
        rubySocket = SocketHelper.getSocket(session[:eterm_name],session[:eterm_pswd])
        res = SocketHelper.getCR(rubySocket,"i",false)
        logger.error "----"+res
        restr = SocketHelper.getCR(rubySocket,cmd,true)
        if rubySocket
          rubySocket.close
          rubySocket=nil
        end
        logger.error "----订票结果="+restr
        restr = CommonHelper.getPnrFromSocketResult(restr,airNo,nil,nil,nil)
        if restr.index(" ") && restr.index(" ")==5
          pnr = restr[0,5]
          status_type = restr[6,2]
        else
          pnr = ""
          status_type = ""
        end
        logger.error "----获取PNR="+pnr+"----"
        if pnr && pnr.length==5
          #保存订单、票、客户积分返利、送票地址等 设置成一个事务
          if CommonHelper.saveMulOrderTicket(1,session[:web_user_id],1,pnr,link_man,link_tel,send_address,send_date,send_time,send_request,
              order_request,jj_address,jj_time,jj_request,tktl_date,tktl_time,affirm_date,fix_type,"web订票","",
              nameString,humanTypeString,cardString,birthdayString,insuranceString,status,trip_type,seat,i_number,
              airNo,fromto,fly_date,fly_time,arr_time,plane_type,position,status_type,price)
            
            result = "订票成功,PNR:#{pnr}"
          else
            result = "PNR已经生成,但是保存订单信息失败,请务必妥善保存PNR:<font color=red>#{pnr}</font>,可利用导入功能将该pnr信息导入系统"
          end
        else
          result = "订票失败,失败原因为:"
          if restr.index("timeout")
            result << "连接服务器超时"
          elsif restr.index("socket is null") || restr==""
            result << "访问服务器失败"
          else
            result << restr
          end
        end
      end
      
      logger.error "result="+result
      result = "{success:true,info:'"+result+"'}"
      render :text=>result, :layout=>false
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
    end
  end

  def getAllPositionByAirNo
    begin
      airNo = params[:air_no]
      flyDate = params[:fly_date]
      personNumber = params[:person_number]
      from = params[:from]
      flyDate = params[:fly_date]
      flyTime = params[:fly_time]
      arrTime = params[:arr_time]
      fromtoDesc =  params[:fromto_desc]
      logger.error "-------------------------------------------------"
      logger.error URI.unescape(fromtoDesc).squish
      planeType = params[:plane_type]
      logger.error airNo
      logger.error flyDate
      logger.error personNumber
      logger.error from
      #转化日期格式
      date_cmd = CommonHelper.getCmdDateFormat(flyDate)
      
      cmd = "AVH/"+airNo+"/"+date_cmd
      #if airways_code && airways_code!=""
      #  cmd << "/"+airways_code
      #end
      #直达
      logger.error cmd
      rubySocket = SocketHelper.getSocket("tao22070","tao22070")
      queryResultStr=nil
      if rubySocket
        queryResultStr = SocketHelper.getCR(rubySocket,cmd,false)
        rubySocket.close
        rubySocket=nil
      end
      queryResultStr = queryResultStr.squish
      logger.error queryResultStr
      positions =  queryResultStr[queryResultStr.index(from)+4..-5]
      logger.error positions
      positionsArray = positions.split(" ");
      
      airways = getPriceDiscount(airNo[0,2])
      jsonStr = "["
      #position price discount
      positionsArray.each do |position|
        if position[1,1] >= personNumber || position[1,1]=="A"
          airways.positions.each do |positionRecord|
            #logger.error position.position_code
            if positionRecord.position_code == position[0,1]
              discount = positionRecord.discount
              jsonStr << "{\"discount\":#{discount},\"position\":\"#{positionRecord.position_code}\",\"price\":1000,'flyDate':'#{flyDate}','fly_time':'#{flyTime}','arr_time':'#{arrTime}','air_no':'#{airNo}','fromto_desc':'#{URI.unescape(fromtoDesc).squish}','plane_type':'#{planeType}'},"
              #logger.error discount
              break
            end
          end
        end
      end
      #jsonStr << "{\"position\":\"#{position}\",\"price\":\"#{price},\"discount\":\"#{discount}\"},"

      jsonStr=jsonStr[0..jsonStr.length-2]+"]"
      jsonStr="{root:"+jsonStr+"}"
      logger.error jsonStr
      render :text=>jsonStr, :layout=>false
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
    end
  end

  def getPersonWebOrders
    begin
      orders = Order.find(:all,:conditions=>["is_locked <> 1 AND customer_id = ?",session[:web_user_id]])
      rootStr = orders.to_json()
      jsonstr="{root:"+rootStr+"}"
      logger.error jsonstr
      render :text=>jsonstr, :layout=>false
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
    end
  end

  def setOfferWebOrderComplete
    begin
      webOrder = WebOrder.find(:first,:conditions=>["is_locked <> 1 AND seller_id = ? AND order_no = ?",session[:web_user_id],params[:order_no]])
      webOrder.status = Constants::WEB_ORDER_STATUS_CLWC
      webOrder.save
      jsonstr="SUCCESS"
      render :text=>jsonstr, :layout=>false
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
    end
  end

  #客户积分查询
  def getCustomersPoint
    begin
      id = session[:web_user_id]
      customer = Customer.find_by_id(id)

      tail_sql = " customer_id="+customer.id.to_s
      tail_sql << " and status='"+Constants::ORDER_STATUS_YFK+"'"
      tail_sql << " and pay_type<>'"+Constants::PAY_TYPE_JF+"' and pay_type<>'"+Constants::PAY_TYPE_QT+"'"
      tail_sql << " and is_locked <> 1"
        
      sql = "select sum(price_sum) as sum from orders where "+tail_sql
      logger.error sql
      expenditure_sum = Order.find_by_sql(sql)[0].sum.to_i
      logger.error "累计消费="+expenditure_sum.to_s
        
      sql = "select sum(point) as point_sum,sum(price) as price_sum,sum(airdrome_tax) as tax_sum,sum(fuel_tax) as fuel_sum from tickets where status='"+Constants::TICKET_STATUS_YCP+"' and order_id in(select id from orders where "+tail_sql+")"
      logger.error sql
        
      ticket = Ticket.find_by_sql(sql)[0]
      point_sum = ticket.point_sum.to_i
      price_sum = ticket.price_sum.to_i
      tax_sum = ticket.tax_sum.to_i
      fuel_sum = ticket.fuel_sum.to_i
        
      logger.error "累计积分="+point_sum.to_s
      logger.error "累计票价="+price_sum.to_s
      logger.error "累计税费="+tax_sum.to_s
      logger.error "累计附加="+fuel_sum.to_s
        
      #统计出订单中所有积分和消费数据 减去积分维护记录中的数据 得到真实的积分和消费数据 再保存到客户表中
      sql = "select sum(point) as point_sum,sum(price) as price_sum,sum(expenditure) as expenditure_sum,sum(tax) as tax_sum,sum(fuel) as fuel_sum  from point_his where customer_id="+customer.id.to_s
      sql << " and is_locked<>1 and point<>0"
      #加
      pointHis = PointHis.find_by_sql(sql+" and options='加'")[0]
      point_sum_add = pointHis.point_sum.to_i
      price_sum_add = pointHis.price_sum.to_i
      expenditure_sum_add = pointHis.expenditure_sum.to_i
      tax_sum_add = pointHis.tax_sum.to_i
      fuel_sum_add = pointHis.fuel_sum.to_i
      #减
      pointHis = PointHis.find_by_sql(sql+" and options='减'")[0]
      point_sum_dec = pointHis.point_sum.to_i
      price_sum_dec = pointHis.price_sum.to_i
      expenditure_sum_dec = pointHis.expenditure_sum.to_i
      tax_sum_dec = pointHis.tax_sum.to_i
      fuel_sum_dec = pointHis.fuel_sum.to_i
        
      point = point_sum + point_sum_add - point_sum_dec
      price = price_sum + price_sum_add - price_sum_dec
      expenditure = expenditure_sum + expenditure_sum_add - expenditure_sum_dec
      tax = tax_sum + tax_sum_add - tax_sum_dec
      fuel = fuel_sum + fuel_sum_add - fuel_sum_dec
        
      logger.error "--当前积分="+point.to_s
      logger.error "--当前票价="+price.to_s
      logger.error "--当前消费="+expenditure.to_s
      logger.error "--当前税费="+tax.to_s
      logger.error "--当前附加="+fuel.to_s
        
      #将历史记录和当前记录加起来组成新的当前记录
      customer.point = point + customer.point_old
      customer.point_his = point_sum + customer.point_his_old
      customer.price = price + customer.price_old
      customer.expenditure = expenditure + customer.expenditure_old
      customer.expenditure_his = expenditure_sum + customer.expenditure_his_old
      customer.tax = tax + customer.tax_old
      customer.fuel = fuel + customer.fuel_old
      if !customer.save
        result = "重新计算客户"+customer.name+"的积分失败"
        logger.error result
      end

      rootStr = customer.to_json(:include=>[:customer_type,:card_type])
      jsonstr="{root:["+rootStr+"]}"
      render :text=>jsonstr, :layout=>false
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
    end 
  end
end
